import React, { useEffect, useState, useRef } from 'react'
import { Button, PageHeader, Steps, Form, Input, Select, message,notification } from "antd"
import { useNavigate,useParams} from 'react-router';
import NewsEditor from '../../../components/news-manage/NewsEditor';
import "./News.css"
import axios from 'axios';
const { Option } = Select
export default function NewsUpdate() {
  const navigator=useNavigate();
  const params=useParams()
  const [current, setCurrent] = useState(0);//控制进度条显示到哪一步
  const [categoryList, setCategoryList] = useState([]);//存储新闻分类下拉菜单
  const [formInfo, setFormInfo] = useState({});//存储第一步表单里的数据
  const [content, setContent] = useState("");//存储第二步新闻详情
  const NewsForm = useRef(null)
  useEffect(() => {
    // 请求新闻分类
    axios.get('/categories').then(res => {
      setCategoryList(res.data)
    })
  }, [])
  useEffect(()=>{
    axios.get(`/news/${params.id}?_expand=category&_expand=role`).then(res=>{
      if(res.data.label){
        res.data.title=res.data.label
      }
     const {title,categoryId,content}=res.data;
     NewsForm.current.setFieldsValue({
        title,
        categoryId
     })
     setContent(content)
    })
},[params.id])
  // 进度条数据
  const items = [
    {
      title: '基本信息',
      description: '新闻标题'
    },
    {
      title: '新闻内容',
      description: "新闻主体内容"
    }, {
      title: '新闻提交',
      description: '保存草稿或提交审核'
    }];
  // 下一步
  const handlerNext = () => {
    if (current === 0) {
      // validateFields()方法是触发表单验证
      NewsForm.current.validateFields().then(res => {
        setFormInfo(res)
        setCurrent(current + 1)
      }).catch(error => {
        console.log(error)
      })
    } else {
      //  如果是第二步
      if (content === "" || content.trim() === "<p></p>") {
        message.error('新闻内容不能位空')
      } else {
        setCurrent(current + 1)
      }
    }
  }
  // 上一步
  const handlePrev = () => {
    setCurrent(current - 1)
  }
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 }
  }
  // 保存到草稿箱
//   const User=JSON.parse(localStorage.getItem('token'));
  const handleSave = (auditState) => {
    axios.patch(`/news/${params.id}`, {
      ...formInfo,
      "content":content,
      "auditState": auditState,  
    //   以下注释的基本都没更新，与添加不是相同的，添加的话是都需要添加进去的额，与后台结构保持一致
    //   "region": User.region?User.region:'全球',
    //   "author": User.username,
    //   "roleId": User.roleId,
      //auditState值为0，存到草稿相，值为1，进行提交审核，值为2，审核成功，值为3，审核失败 
    //   "publishState": 0,
    //   "createTime": Date.now(),
    //   "star":0,
    //   "view": 0,
    //   "publishTime": 0  //--->发布时间
    }).then(()=>{
      // 如果值为0跳到草稿箱，值为1跳到审核列表
      navigator(auditState===0?'/news-manage/draft':'/audit-manage/list')
      notification.info({
        message: `通知`,
        description:`您可以到${auditState===0?'草稿箱':'审核列表'}中查看您的新闻`,
        placement:'bottomRight',
      });
    })
  }
  return (
    <div>
      <PageHeader className="site-page-header" title="更新新闻"  onBack={() => window.history.back()}/>

      <Steps items={items} current={current} />
      <div style={{ marginTop: '50px' }}>
        <div className={current === 0 ? '' : 'hidden'}>
          <Form
            {...layout}
            name="basic"
            ref={NewsForm}
          >
            <Form.Item

              name="title"
              label="新闻标题"
              rules={[
                {
                  required: true,
                  message: '请输入新闻标题'
                }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="categoryId"
              label="新闻分类"
              rules={[
                {
                  required: true,
                  message: '请选择新闻分类'
                }
              ]}
            >
              <Select>
                {
                  categoryList.map(item => <Option value={item.id} key={item.id}>{item.label}</Option>)
                }
              </Select>
            </Form.Item>
          </Form>
        </div>
      </div>
      <div className={current === 1 ? '' : 'hidden'}>
        {/* 新闻编辑组件--->编辑内容，就是由该子组件传过来的 */}
        <NewsEditor getContent={(values) => { setContent(values) }} content={content}></NewsEditor>
      </div>
      <div style={{ marginTop: '50px' }}>
        {
          current === 2 && <span>
            <Button type="primary" onClick={() => handleSave(0)}>保存到草稿箱</Button>
            <Button danger  onClick={() => handleSave(1)}>提交审核</Button>
          </span>
        }
        {
          current < 2 && <Button type="primary" onClick={handlerNext}>下一步</Button>
        }
        {
          current > 0 && <Button onClick={handlePrev}>上一步</Button>
        }
      </div>
    </div>
  )
}
